package com.studyroom.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String fromEmail; // 从配置中获取发件人邮箱，确保一致性
    
    public void sendVerificationCode(String to, String code) {
        try {
            log.info("准备发送验证码邮件到: {}, 发件人: {}", to, fromEmail);
            
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail); // 使用配置的邮箱作为发件人
            message.setTo(to);
            message.setSubject("自习室预约系统 - 密码重置验证码");
            message.setText("您的验证码是: " + code + "，有效期10分钟，请勿告知他人。");
            
            mailSender.send(message);
            log.info("验证码邮件已成功发送至: {}", to);
        } catch (Exception e) {
            log.error("发送验证码邮件失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送验证码邮件失败: " + e.getMessage());
        }
    }
} 